package com.yanyu.space.common.sleuth;


import com.yanyu.space.common.core.bootlog.BootstrapLogContext;
import com.yanyu.space.common.core.constants.SpaceConstants;
import com.yanyu.space.common.core.yaml.YamlPropertySourceFactory;
import com.yanyu.space.common.sleuth.rocket.SpaceNewDestinationBindingCallback;
import com.yanyu.space.common.sleuth.rocket.StreamBridgeAspect;
import com.yanyu.space.common.sleuth.web.SamplerPredicater;
import com.yanyu.space.common.sleuth.web.SkipSamplerPredicaterHandler;
import com.yanyu.space.common.sleuth.web.response.TraceIdResponseBodyAdvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import java.util.List;

/***
 * @author yanyu
 */
@Configuration
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:" + SpaceConstants.Properties.SLEUTH_PROP)
public class SleuthAutoConfig {

    public SleuthAutoConfig(@Value("${spring.zipkin.enabled:true}") Boolean zipkinEnabled,
                            @Value("${spring.zipkin.sender.type}") String senderType) {
        if (zipkinEnabled) {
            BootstrapLogContext.put("zipkin", String.format("开启zipkin功能, 发送类型 -> %s", senderType));
        }
    }

    @Bean("sleuthHttpServerSampler")
    public SkipSamplerPredicaterHandler skipOptionsSampler(@Autowired(required = false) List<SamplerPredicater> predicaters) {
        return new SkipSamplerPredicaterHandler(predicaters);
    }

    @Bean
    public SpaceNewDestinationBindingCallback spaceNewDestinationBindingCallback() {
        return new SpaceNewDestinationBindingCallback();
    }

    @Configuration
    @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
    class TraceIdResponseBodyAdviceConfig {

        @Bean
        public TraceIdResponseBodyAdvice traceIdResponseBodyAdvice() {
            return new TraceIdResponseBodyAdvice();
        }
    }
}
